package com.touzi.servlets;

import com.touzi.beans.dbs.liushui.Liushui;
import com.touzi.beans.dbs.tixian.Tixian;
import com.touzi.constants.DbCons;
import com.touzi.mapper.LiushuiMapper;
import com.touzi.mapper.TixianMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LiushuiServlet")
public class LiushuiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = " ";
        method = request.getParameter("method");

        if (method.equals("showlist")) {
            showList(request, response);
        }
    }

    private void showList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SqlSession sqlSession = ((SqlSessionFactory) getServletContext().getAttribute(DbCons.DB_FACTORY)).openSession();
        LiushuiMapper mapper = sqlSession.getMapper(LiushuiMapper.class);
        int page = 1;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (Exception e) {
            e.printStackTrace();
            page = 1;
        }
        int total = mapper.countAll();
        if (total <= 0) {
            total = 1;
        }
        int pages = (int) Math.ceil(total / 30.0);
        if (page < 1) {
            page = 1;
        } else if (page >= pages) {
            page = pages;
        }

        List<Liushui> list = mapper.getList((page - 1) * 30);
        sqlSession.close();

        request.setAttribute("page", page);
        request.setAttribute("pages", pages);
        request.setAttribute("total", total);
        request.setAttribute("userlist", list);
        request.getRequestDispatcher("/WEB-INF/jsp/liushui.jsp").forward(request, response);
    }
}
